import { ref, nextTick } from 'vue'
import type { Reactive } from 'vue'

type IState = '10' | '20' | '30' | '40' | '50' | '60'

const stateTagCN = {
  '10': '待操作',
  '20': '匹配成功',
  '30': '匹配失败',
  '40': '重命名成功',
  '50': '无权访问',
  '60': '文件不存在'
}

interface IStateTagType {
  [key: string]: 'success' | 'warning' | 'info' | 'primary' | 'danger'
}

const stateTagType: IStateTagType = {
  '10': 'primary',
  '20': 'success',
  '30': 'danger',
  '40': 'success',
  '50': 'danger',
  '60': 'danger'
}

// 当前编辑的单元格
const curEditCell = ref<string>()

// 单元格相关配置
export default function useTableCellAction() {
  // 拼接原文件名
  function getOriginalFileName(row: ITableDataItem) {
    if (row.original.ext) {
      return `${row.original.name}.${row.original.ext}`
    } else {
      return `${row.original.name}`
    }
  }

  // 获取新文件名
  function getNewestFileName(row: ITableDataItem) {
    if (row.newest.ext) {
      return `${row.newest.name}.${row.newest.ext}`
    } else {
      return `${row.newest.name}`
    }
  }

  // 拼接新文件名后缀
  function getNewestFileNameExt(row: ITableDataItem) {
    return `${row.newest.ext}`
  }

  // 单元格点击
  async function handleCellClick(
    row: Reactive<ITableDataItem>,
    column: any,
    _cell: HTMLTableCellElement,
    event: Event
  ) {
    if (column.property === 'newFileName') {
      curEditCell.value = row.fullPath
      const el = event.target as HTMLElement
      // 获取父元素
      const parentEl = el.parentElement
      await nextTick()
      if (parentEl) {
        const inputEl = parentEl.querySelector(
          '.el-input__inner'
        ) as HTMLInputElement
        if (inputEl) {
          inputEl.focus()
        }
      }
    }
  }

  function getStateText(state: IState) {
    return stateTagCN[state]
  }

  function getStateType(state: IState) {
    return stateTagType[state]
  }

  function setCellStyle({ column }) {
    if (column.property === 'newFileName') {
      return { background: '#F5F7FA' }
    }
    return { background: '#fff' }
  }

  return {
    getOriginalFileName,
    getNewestFileName,
    getNewestFileNameExt,
    curEditCell,
    handleCellClick,
    getStateText,
    getStateType,
    setCellStyle
  }
}
